package com.hjt.gulimall.auth.service.impl;

import com.hjt.common.constant.AuthConstant;
import com.hjt.common.utils.RandomUtils;
import com.hjt.gulimall.auth.feign.ThreePartyFeignService;
import com.hjt.gulimall.auth.service.RegisterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.concurrent.TimeUnit;

/**
 * @author:97007
 * @date:2021/9/28 18:35
 */
@Service
public class RegisterServiceImpl implements RegisterService {
    @Autowired
    ThreePartyFeignService threePartyFeignService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean sendCode(String email) {
        // 1。存入缓存
        // 保存到redis中,5分钟有效
        String key = AuthConstant.MSM_CODE_CACHE_PREFIX+":"+email;
        String value = redisTemplate.opsForValue().get(key);
        // 如果没过期
        if (StringUtils.hasLength(value)) {
            // 2、接口防刷
            // 60s内不能再次发送
            long l = Long.parseLong(value.split("_")[1]);
            // 如果发送间隔小于指定的值，返回false
            if ((System.currentTimeMillis() - l)/1000 < AuthConstant.SEND_INTERVAL) {
                return false;
            }
        }
        // (过期或者超过发送间隔)发送验证码
        String code = RandomUtils.getRandomCode(AuthConstant.CODE_BITS)+"_"+System.currentTimeMillis();
        threePartyFeignService.sendCode(email,code.split("_")[0]);
        // 保存到缓存中
        redisTemplate.opsForValue().set(key, code,AuthConstant.SEND_INTERVAL,TimeUnit.SECONDS);
        return true;

    }

    @Override
    public boolean verifyCode(String email,String code) {
        String value = redisTemplate.opsForValue().get(AuthConstant.MSM_CODE_CACHE_PREFIX + ":" + email);
        if (StringUtils.hasLength(value)) {
            return code.equals(value.split("_")[0]);
        } else {
            return false;
        }
    }

    @Override
    public void deleteCode(String email) {
        redisTemplate.delete(AuthConstant.MSM_CODE_CACHE_PREFIX + ":" + email);
    }
}
